package com.example.module_home.vm

import com.example.lib_common.view.vm.BaseViewModel
import com.example.module_home.api.HomeApiServer
import com.example.module_home.entity.HouseEntity
import com.example.module_home.model.HomeRepository
import com.example.module_home.model.HomeResultData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HouseViewModel @Inject constructor(
    private val apiServer: HomeApiServer
):BaseViewModel<HomeRepository,HomeResultData<List<HouseEntity>>>(){
    fun getHouse(){
        mViewModelScope.launch(mDispatcher){
            try {
                val getHouse = apiServer.getHouse()
                val homeResultData = HomeResultData(
                    state = getHouse.state,
                    msg = getHouse.msg,
                    data = getHouse.data
                )
                mSuccessLiveData.postValue(homeResultData)
            } catch (e: Exception) {
                mErrorLiveData.postValue("请求失败:${e.message}")
            }
        }
    }

    fun getQueryHouseId(regionId :Int){
        mViewModelScope.launch(mDispatcher){
            try {
                val houseId = apiServer.getQueryHouseId(regionId)
                val res = HomeResultData(
                    state = houseId.state,
                    msg = houseId.msg,
                    data = houseId.data
                )
                mSuccessLiveData.postValue(res)
            } catch (e: Exception) {
                mErrorLiveData.postValue("查询失败:${e.message}")
            }
        }
    }


    fun getHouseSearch(keyword:String){
        mViewModelScope.launch(mDispatcher){
            try {
                val search = apiServer.getHouseSearch(keyword)
                val resultData = HomeResultData(
                    search.state,
                    search.data,
                    search.msg
                )
                mSuccessLiveData.postValue(resultData)
            } catch (e: Exception) {
                mErrorLiveData.postValue("搜索失败:${e.message}")
            }
        }
    }
}